﻿using MediatR;
using RBAC.Api.Demain.ContentManagement;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.ContentManagement;
using RBAC.Api.Read.Dto;

namespace RBAC.Api.Read.CommandHandler.ContentManagement
{
    public class GetDepartmentsCommandHandler : IRequestHandler<GetDepartmentsCommand, APIResult<List<CascadeItem>>>
    {
        private readonly IBaseRepositry<DepartmentModel> baseRepositry;

        public GetDepartmentsCommandHandler(IBaseRepositry<DepartmentModel> baseRepositry)
        {
            this.baseRepositry = baseRepositry;
        }
        public Task<APIResult<List<CascadeItem>>> Handle(GetDepartmentsCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<CascadeItem>> result= new APIResult<List<CascadeItem>>();
            result.Code = ResultCode.Success;
            result.Message = "获取科室成功";

            var list = baseRepositry.GetAll().ToList();
            result.Data = GetCascade(0, list);

            return Task.FromResult(result);
        }
        /// <summary>
        /// 获取科室(递归)
        /// </summary>
        /// <param name="parentId">父级编号</param>
        /// <param name="departments">部门信息</param>
        /// <returns>返回级联程序集合</returns>
        public List<CascadeItem> GetCascade(int parentId, List<DepartmentModel> departments)
        {
            var result = departments.Where(x => x.ParentId == parentId);

            List<CascadeItem> list = new List<CascadeItem>();

            foreach (var item in result)
            {
                list.Add(new CascadeItem
                {
                    Values = item.Id,
                    Label = item.Name,
                    Children = GetCascade(item.Id,departments)
                });
            }
            return list;
        }
    }
}
